package com.meila.cms.services.impl;
 
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.meila.cms.entity.AjaxObj;
import com.meila.cms.entity.Car;
import com.meila.cms.entity.Dict;
import com.meila.cms.entity.PartListDesign;
import com.meila.cms.model.CarDesignModel;
import com.meila.cms.model.CarInstructionsDesignModel;
import com.meila.cms.model.CarModel;
import com.meila.cms.model.SQLAdapterModel;
import com.meila.cms.model.UserModel;
import com.meila.cms.services.ICarDesignService;
import com.meila.cms.util.Content;
import com.meila.cms.util.HtmlUtil;
import com.meila.cms.util.HttpUtils;
import com.meila.cms.util.ResourceLoader;
import com.meila.cms.util.StringUtil;
import com.meila.cms.util.ZipUtil;
import com.meila.cms.util.config.Property;
import com.meila.cms.util.image.HtmlImageGenerator;
import com.meila.cms.util.json.JsonUtil2;
import com.meila.cms.util.page.PageBoundsUtil;
import com.meila.cms.util.page.Pager;
import com.meila.cms.util.page.SystemContext;
import com.meila.cms.util.pdf.PdfDocumentGenerator;
 

@Service
public class CarDesignService extends BaseService implements ICarDesignService {

		
	@Override
	public Pager<CarDesignModel> listCarDesign(CarDesignModel carDesignModel) {
		// TODO Auto-generated method stub
 
		SystemContext.setPageSize(2);
		PageBounds pageBounds = PageBoundsUtil.PageBoundsOrderExtend("createTime.desc,updateTime.desc");
		 
	    UserModel user=getLoginUser();
		if(!StringUtil.isEmpty(user)){
			carDesignModel.setUserid(user.getId());
		}
		
		int count =	carDesignMapper.findCarDesignCount(carDesignModel, pageBounds);

	
		List<CarDesignModel> list = carDesignMapper.findCarDesign(carDesignModel,pageBounds);
 
		Pager<CarDesignModel> pages = new Pager<CarDesignModel>(count,list);
 
		
		return pages;
	}

	/**
	 * 修改车身logo时调用
	 */
	@Override
	public AjaxObj updateCarDesign1(CarDesignModel carDesignModel,HttpServletRequest request) {
		// TODO Auto-generated method stub
		AjaxObj  ajaxObj=new AjaxObj();
		try {
			carDesignModel.setUpdatetime(new Date());
 
			//合并图片并且上传
			CarDesignModel  carDesignModel1;
		    if(carDesignModel.getType()==2){
		    	
		    	
		    	 {
		    	    carDesignModel1=carDesignMapper.selectByPrimaryKey(carDesignModel.getId());
					//设置车身内容
		    	    
		    		carDesignModel1.setContent(carDesignModel.getContent());
		    		if(carDesignModel.getLogopart()==1){
		    			carDesignModel1.setPicid(carDesignModel1.getCarsidepic());
		    			carDesignModel.setCarsidelogo(carDesignModel.getContent());
		    		}else if (carDesignModel.getLogopart()==2) {
		    			carDesignModel1.setPicid(carDesignModel1.getCarfrontpic());
		    			carDesignModel.setCarfrontlogo(carDesignModel.getContent());
					}else if (carDesignModel.getLogopart()==3) {
						carDesignModel1.setPicid(carDesignModel1.getCarafterpic());
						carDesignModel.setCarafterlogo(carDesignModel.getContent());
					}
		    		
		    		if(!StringUtil.isEmpty(carDesignModel1.getCarcorlor())){
		    			carDesignModel1.setCarcorlor(dictUtil.getNameByValue("CarColor", carDesignModel1.getCarcorlor()));
		    		}else {
		    			//默认为白色
		    			carDesignModel1.setCarcorlor("#FFFFFF");
					}
		    		
		    	}

		    	
		    	//得到图片imageKedit
		    	String path = request.getContextPath();
		    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		    	
		    	String html =  Content.htmlTemplate.replace("backgroundcolor",carDesignModel1.getCarcorlor());
		    	html=html.replace("baseurl",basePath);
		    	html=html.replace("content",carDesignModel1.getContent());
 
	            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
	            imageGenerator.loadHtml(html);
	            BufferedImage imageKedit =  imageGenerator.getBufferedImage();

	            //得到图片imageOrigin
	            URL u = new URL(Property.getProperty("FILESERVER_PATH")+"?id="+carDesignModel1.getPicid());
	            BufferedImage imageOrigin = ImageIO.read(u);
 
	            //合成新的图片
 	            Graphics g=imageOrigin.getGraphics();
                g.drawImage(imageKedit,imageOrigin.getWidth()-imageKedit.getWidth(),imageOrigin.getHeight()-imageKedit.getHeight(),imageKedit.getWidth(),imageKedit.getHeight(),null);
                 
                
              
                 //替换文件服务器上的图片
	           	 URL url = new URL(Property.getProperty("FILESERVER_REPLACE")+"?id="+carDesignModel1.getPicid());
	             HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
	             conn.setDoOutput(true);  
	             conn.setUseCaches(false);  
	             conn.setRequestMethod("POST");  
	             conn.setRequestProperty("Content-Type","text/html");  
	             conn.setRequestProperty("Cache-Control","no-cache");  
	             conn.setRequestProperty("Charsert", "UTF-8");   
	             conn.connect();  
	             conn.setConnectTimeout(10000);  
	             OutputStream out =conn.getOutputStream();  
	             ByteArrayOutputStream os=new ByteArrayOutputStream();
	             ImageIO.write(imageOrigin, "png", os); //利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
	             byte b[]=os.toByteArray();
	     
	             ByteArrayInputStream in   = new ByteArrayInputStream(b); 

	             int bytes = 0;  
	             byte[] buffer = new byte[1024];  
	             while ((bytes = in.read(buffer)) != -1) {  
	                 out.write(buffer, 0, bytes);  
	             }  
	             in.close();  
	             out.flush();  
	             out.close();   
	        
	             conn.getInputStream();  
	             conn.disconnect();  
 
		    }
	    	
	    	//更新车的参数
	    	carDesignMapper.updateByPrimaryKeySelective(carDesignModel);
	    	
			ajaxObj.setMsg("操作成功");
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		
		return ajaxObj;
	}


	/**
	 * 之前未选过车型时调用
	 */
	@Override
	public AjaxObj updateCarDesign2(CarDesignModel carDesignModel,
			HttpServletRequest request) {
		
		// TODO Auto-generated method stub
		AjaxObj  ajaxObj=new AjaxObj();
	   	String path = request.getContextPath();
    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    	
    	
		try {
			UserModel user=getLoginUser();
			if(!StringUtil.isEmpty(user)){
				carDesignModel.setUserid(user.getId());
			}
 
			Map<String, String> params =new HashMap<String, String>();
	 		params.put("userName", user.getPhone());
			Car car=carMapper.selectByPrimaryKey(carDesignModel.getCarid());
 
 
			//这些属性不会在选择车型的时候不会被修改所以从原来的t_car表里取
			carDesignModel.setCarsidelogo(car.getCarsidelogo());
			carDesignModel.setCarfrontlogo(car.getCarfrontlogo());
			carDesignModel.setCarfrontlogo(car.getCarfrontlogo());
		    carDesignModel.setUpdatetime(new Date());
		 
		    
			//根据原生图片复制新的图片
	 	    String result= HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getCarsidepic(), params);
	        JSONObject jsonObject= new JSONObject(result);
	        Integer id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
	    	carDesignModel.setCarsidepic(id);
	        
	    
	    	result=HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getCarfrontpic(), params);
		    jsonObject= new JSONObject(result);
		    id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
			carDesignModel.setCarfrontpic(id);
			
			result=HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getCarafterpic(), params);
		    jsonObject= new JSONObject(result);
		    id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
			carDesignModel.setCarafterpic(id);
			
			//复制3d文档
			if(!StringUtil.isEmpty(car.getThreedid())){
				result=HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getThreedid(), params);
			    jsonObject= new JSONObject(result);
			    id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
				carDesignModel.setThreedid(id);
			}
 
		    //更新用户存储容量
			Integer[] fileids={car.getCarafterpic(),car.getCarfrontpic(),car.getCarsidepic(),car.getPlanid(),car.getThreedid()};
			updateMemory(fileids,true);
 
			
			//向整车设计零件清单表添加数据
			PartListDesign partListDesign=new PartListDesign();
			partListDesign.setCarid(carDesignModel.getCarid());
			partListDesign.setDesignid(carDesignModel.getId());
			partListDesignMapper.addPartList(partListDesign);
			
			//向整车设计工艺指令表添加数据
			CarInstructionsDesignModel carInstructionsDesignModel=new CarInstructionsDesignModel();
			carInstructionsDesignModel.setCarid(carDesignModel.getCarid());
			carInstructionsDesignModel.setDesignid(carDesignModel.getId());
			carInstructionsDesignMapper.addInstructionsList(carInstructionsDesignModel);
			
			carDesignMapper.updateByPrimaryKeySelective(carDesignModel);
			
			ajaxObj.setMsg("操作成功");
			
		} catch (Exception e) {
			// TODO: handle exception
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		
		
		return ajaxObj;
	}
	
	/**
	 * 之前选过车型时调用
	 */
	@Override
	public AjaxObj updateCarDesign3(CarDesignModel carDesignModel,
			HttpServletRequest request) {
		// TODO Auto-generated method stub
		AjaxObj  ajaxObj=new AjaxObj();
	 
		
		try {
			
			//前一次数据库里存的数据
			CarDesignModel	carDesignModel2 = carDesignMapper.selectByPrimaryKey(carDesignModel.getId());
            
			
			//选择的车型和前一次不一样选择
			if(carDesignModel2.getCarid()!=carDesignModel.getCarid()){
			   
				UserModel user=getLoginUser();
				Map<String, String> params =new HashMap<String, String>();
		 		params.put("userName", user.getPhone());
		 		
				Car  car = carMapper.selectByPrimaryKey(carDesignModel.getCarid());
				//根据原生图片复制新的图片
		 	    String result= HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getCarsidepic(), params);
		        JSONObject jsonObject= new JSONObject(result);
		        Integer id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
		    	carDesignModel.setCarsidepic(id);
		    	carDesignModel.setCarsidelogo("");
		    
		    	result=HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getCarfrontpic(), params);
			    jsonObject= new JSONObject(result);
			    id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
				carDesignModel.setCarfrontpic(id);
				carDesignModel.setCarfrontlogo("");
				
				result=HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getCarafterpic(), params);
			    jsonObject= new JSONObject(result);
			    id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
				carDesignModel.setCarafterpic(id);
				carDesignModel.setCarafterlogo("");
				
				//复制3d文档
				if(!StringUtil.isEmpty(car.getThreedid())){
					result=HttpUtils.postUrlAsString(Property.getProperty("FILESERVER_COPY")+"?id="+car.getThreedid(), params);
				    jsonObject= new JSONObject(result);
				    id=Integer.valueOf(new JSONObject(jsonObject.get("data").toString()).get("id").toString());
					carDesignModel.setThreedid(id);
				}
				
				
			    //更新用户存储容量
				Integer[] fileids={car.getCarafterpic(),car.getCarfrontpic(),car.getCarsidepic(),car.getPlanid(),car.getThreedid()};
				updateMemory(fileids,true);
	 
				
				//删除之前的数据再向整车设计零件清单表添加数据
				partListDesignMapper.deleteByDesignId(carDesignModel.getId());
				
				PartListDesign partListDesign=new PartListDesign();
				partListDesign.setCarid(carDesignModel.getCarid());
				partListDesign.setDesignid(carDesignModel.getId());
				partListDesignMapper.addPartList(partListDesign);
				
				//删除之前的数据再向向整车设计工艺指令表添加数据
				carInstructionsDesignMapper.deleteByDesignId(carDesignModel.getId());
				
				CarInstructionsDesignModel carInstructionsDesignModel=new CarInstructionsDesignModel();
				carInstructionsDesignModel.setCarid(carDesignModel.getCarid());
				carInstructionsDesignModel.setDesignid(carDesignModel.getId());
				carInstructionsDesignMapper.addInstructionsList(carInstructionsDesignModel);
				

			}
			
			
			carDesignMapper.updateByPrimaryKeySelective(carDesignModel);

			ajaxObj.setMsg("操作成功");
			
		} catch (Exception e) {
			// TODO: handle exception
			ajaxObj.setResult(false);
			ajaxObj.setMsg("操作失败");
			e.printStackTrace();
		}
		
		
		return ajaxObj;
	}
 
	
	 
	@Override
	public void carDesignToModify(CarDesignModel carDesignModel, Model model) {
		// TODO Auto-generated method stub
 
		
		//未选车型
		if(!StringUtil.isEmpty(carDesignModel.getCarid())){
			
		}else{
		//已选车型
			carDesignModel = carDesignMapper.selectByPrimaryKey(carDesignModel.getId());
		}
		
		if(StringUtil.isEmpty(carDesignModel.getCartype())){
			carDesignModel.setCartype(1);
		}else {
			carDesignModel.setCartype(carDesignModel.getCartype());
		}
		
		//车型
		Dict dict = new Dict();
		dict.setCategory("CarType");
		List<Dict> dictList=dictMapper.selectSelective(dict);
		model.addAttribute("dictList",dictList);
		
		//车身颜色
		dict.setCategory("CarColor");
		List<Dict> carColorList=dictMapper.selectSelective(dict);
		model.addAttribute("carColorList",carColorList);
		
		
		//备选车辆
		model.addAttribute("carList",getCarList(carDesignModel));
		
		carDesignModel.setCartypeName(dictUtil.getNameByValue("CarType", carDesignModel.getCartype().toString()));
		model.addAttribute("carDesignModel",carDesignModel);
	}

	@Override
	public List getCarList(CarDesignModel carDesignModel) {
		// TODO Auto-generated method stub
		CarModel carModel = new CarModel();
		if(StringUtil.isEmpty(carDesignModel.getCartype())){
			carModel.setCartype(1);
		}else {
			carModel.setCartype(carDesignModel.getCartype());
		}
		 
		List<CarModel> carList=carMapper.selectSelective(carModel);
		return carList;
	}
	@Override
	public ResponseEntity<byte[]> downloadFileBychose(String designid,
			Integer[] chose, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		CarDesignModel carDesignModel=carDesignMapper.selectByPrimaryKey(Integer.valueOf(designid));
		
	    HttpHeaders headers = new HttpHeaders();    
	    File file;
	    ResponseEntity<byte[]> result = null;
		
		
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String template_path;
        // classpath 路径
    	String  outputFileClass = ResourceLoader.getPath("");
       	long    timp;
       	String  outputFile = null;
 
		String filenames[]=new String[chose.length];
		File[] files =new File[chose.length];
        try {
				for (int i = 0; i < chose.length; i++) {
					
					if(((carDesignModel.getCarsidelogo()==null && carDesignModel.getCarfrontlogo()==null &&carDesignModel.getCarafterpic()==null && chose[i]==1))
							||(carDesignModel.getThreedid()==null && chose[i]==2)){
						continue;
					}
					
					outputFile = new File(outputFileClass).getParentFile().getParent();
					timp = System.currentTimeMillis();
					
					switch ( chose[i]) {
					case 1:
						 filenames[i]="2D文档.pdf";
						 template_path = basePath+"front/carDesign/carDesignpdf?export=true&designid="+designid;
						 outputFile =outputFile+"/resources/download/"+timp+".pdf";
						 PdfDocumentGenerator.generate(HtmlUtil.findHtmlStringByURL(template_path), outputFile);
						break;
 
					case 2:
					        filenames[i]="3D文档.stp";
						    outputFile = outputFile+"/resources/download/"+timp+".stp";
							//先下载到服务器目录
						    HttpUtils.downloadFile(outputFile, Property.getProperty("FILESERVER_PATH")+"?id="+carDesignModel.getThreedid());
					    	break;
					case 3:
						 filenames[i]="零件清单.pdf";
						 template_path = basePath+"front/carDesign/partListpdf?export=true&designid="+designid;
						 outputFile =outputFile+"/resources/download/"+timp+".pdf";
						 //先生成到服务器目录
						 PdfDocumentGenerator.generate(HtmlUtil.findHtmlStringByURL(template_path), outputFile);
						break;
					case 4:
						 filenames[i]="工艺指令.pdf";
						 template_path = basePath+"front/carDesign/craftOrderpdf?export=true&designid="+designid;
						 outputFile =outputFile+"/resources/download/"+timp+".pdf";
						 //先生成到服务器目录
						 PdfDocumentGenerator.generate(HtmlUtil.findHtmlStringByURL(template_path), outputFile);
						break;
					default:
						break;
					}
					
			        //记录下载到服务器的目录
				    files[i] = new File(outputFile);
				}
		
				//打包下载到服务器目录
				timp = System.currentTimeMillis();
				outputFile =  new File(outputFileClass).getParentFile().getParent()+"/resources/download/"+carDesignModel.getName()+"_"+timp+".zip";
				ZipUtil.compressFilesToZip(files, outputFile, filenames);
				
				//设置响应头，控制浏览器下载该文件
				file = new File(outputFile);  
		        String fileName=new String((carDesignModel.getName()+"_"+timp+".zip").getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
		        headers.setContentDispositionFormData("attachment", fileName); 
		        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
		        result=  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
		                headers, HttpStatus.CREATED);
		
		        file.deleteOnExit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
        
		return result;
	}

	@Override
	public void carLogoModify(CarDesignModel carDesignModel, Model model) {
		// TODO Auto-generated method stub
		carDesignModel = carDesignMapper.selectByPrimaryKey(carDesignModel.getId());
		
		carDesignModel.setCartypeName(dictUtil.getNameByValue("CarType", carDesignModel.getCartype().toString()));
		
		//车身颜色
		Dict dict = new Dict();
		dict.setCategory("CarColor");
		List<Dict> carColorList=dictMapper.selectSelective(dict);
		model.addAttribute("carColorList",carColorList);
		
		model.addAttribute("carDesignModel",carDesignModel);
	}

	@Override
	public CarDesignModel carDesignByid(Integer id) {
		// TODO Auto-generated method stub
		CarDesignModel carDesignModel = carDesignMapper.selectByPrimaryKey(id);
		
		return carDesignModel;
	}

	@Override
	public ResponseEntity<byte[]> exportPDF(String designid,
			HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String template_path = basePath+"front/carDesign/carDesignpdf?export=true&designid="+designid;
        // classpath 路径
    	String outputFileClass = ResourceLoader.getPath("");
    	
    	long timp=System.currentTimeMillis();
	    String    outputFile = new File(outputFileClass).getParentFile().getParent()+"/resources/download/"+timp+".pdf";
       
	    HttpHeaders headers = new HttpHeaders();    
	    File file;
	    ResponseEntity<byte[]> result = null;
		try {
			PdfDocumentGenerator.generate(HtmlUtil.findHtmlStringByURL(template_path), outputFile);
			
			//设置响应头，控制浏览器下载该文件
	        file = new File(outputFile);  
	        String fileName=new String("carDesign.pdf".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
	        headers.setContentDispositionFormData("attachment", fileName);   
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   

	        result=  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
	                headers, HttpStatus.CREATED);
	        
	        file.deleteOnExit();
	        
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
 
		}
        return result;  
	}

	@Override
	public AjaxObj delCarDesign(CarDesignModel carDesignModel) {
		// TODO Auto-generated method stub
		
		AjaxObj  ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		try {
			carDesignModel.setDel(1);
			carDesignModel.setUpdatetime(new Date());
			carDesignMapper.updateByPrimaryKey(carDesignModel);
			
			SQLAdapterModel sql=new SQLAdapterModel();
			sql.setSql("update t_car_instructions_design set del=1 where designId="+carDesignModel.getId());
			dictMapper.updateBySQL(sql);
 
			sql.setSql("update t_parts_list_design set del=1 where designId="+carDesignModel.getId());
			dictMapper.updateBySQL(sql);
			
			
		}catch (Exception e) {
			// TODO: handle exception
			ajaxObj.setMsg("删除时出错");
			ajaxObj.setResult(false);
			e.printStackTrace();
		}
		
		return ajaxObj;
	}

	@Override
	public void addCarDesign(CarDesignModel carDesignModel, Model model) {
		// TODO Auto-generated method stub
		//车型
		Dict dict = new Dict();
		dict.setCategory("CarType");
		List<Dict> dictList=dictMapper.selectSelective(dict);
		model.addAttribute("dictList",dictList);
		
		//车身颜色
		dict.setCategory("CarColor");
		List<Dict> carColorList=dictMapper.selectSelective(dict);
		model.addAttribute("carColorList",carColorList);
		
		//备选车辆
		model.addAttribute("carList",getCarList(carDesignModel));
		
		//添加整车设计的数据
		carDesignModel.setUserid(getLoginUser().getId());
		carDesignModel.setUpdatetime(new Date());
		carDesignModel.setCreatetime(new Date());
		carDesignModel.setDel(0);
		carDesignMapper.insertSelective(carDesignModel);
		if(StringUtil.isEmpty(carDesignModel.getCartype())){
			carDesignModel.setCartype(1);
		} 
		
		carDesignModel.setCartypeName(dictUtil.getNameByValue("CarType", carDesignModel.getCartype().toString()));
		model.addAttribute("carDesignModel",carDesignModel);
	}

 
	/**
	 * 计算私有容量
	 * @param fileids
	 * @param isupdate
	 * @return
	 */
	public AjaxObj updateMemory(Integer fileids[],Boolean isupdate) {
 
		AjaxObj ajaxObj=new AjaxObj();
	    try {
			int sum=0;
	    	for (int i = 0; i < fileids.length; i++) {
 
				   String  url=Property.getProperty("FILESERVER_GETDATA")+fileids[i];

				   String result =	HttpUtils.getUrlAsString(url);
			       JSONObject jsonObject=JsonUtil2.stringToJSONObject(result);
			       int fileSize= jsonObject.get("fileSize")==null? 0:Integer.valueOf(jsonObject.get("fileSize").toString());
			       sum=sum+fileSize;
	    	}
		   
		   UserModel userModel = getLoginUser();
		   if(userModel.getRemianSpace()-sum > 0){
			   if(isupdate){
				   userModel.setRemianSpace(userModel.getRemianSpace()-sum);
				   userMapper.updateByPrimaryKeySelective(userModel);
				   userModel = userMapper.selectByPhone(userModel.getPhone());
				   session.setAttribute("loginUser", userModel);
			   }
			   ajaxObj.setResult(true);
			   
		   }else {
			   ajaxObj.setResult(false);
			   ajaxObj.setMsg("容量不足");
		   }
	    	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ajaxObj.setResult(false);
			   ajaxObj.setMsg("更新容量时失败");
		}
	    return  ajaxObj;
		
	}

}
